const { Class, Teacher, Student } = require('../models/db');

const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

const mapClassToClient = (c) => ({
  id: c._id?.toString(),
  name: c.className,
  className: c.className,
  academy: c.academy,
  stage: c.stage,
  advisorId: c.advisor ? c.advisor._id?.toString() : undefined,
  advisorName: c.advisor ? c.advisor.name : undefined,
  lecturerId: c.lecturer ? c.lecturer._id?.toString() : undefined,
  lecturerName: c.lecturer ? c.lecturer.name : undefined,
  studentCount: c.studentCount || 0,
  students: c.students ? c.students.map(s => ({
    id: s._id?.toString(),
    studentId: s.studentId,
    name: s.name
  })) : [],
  // 班主任就是导员
  classTeacher: c.advisor ? c.advisor.name : undefined,
  createdAt: c.createdAt ? new Date(c.createdAt).toISOString() : undefined,
  updatedAt: c.updatedAt ? new Date(c.updatedAt).toISOString() : undefined,
});

const mapClientToClass = (body) => ({
  className: body.className,
  academy: body.academy,
  stage: body.stage,
  advisor: body.advisorId,
  lecturer: body.lecturerId,
  updatedAt: new Date(),
});

exports.getAllClasses = async (req, res) => {
  try {
    const { page = 1, limit = 20, academy, stage } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const query = {};
    
    if (academy) query.academy = academy;
    if (stage) query.stage = stage;
    
    const classes = await Class.find(query)
      .populate('advisor', 'name teacherId')
      .populate('lecturer', 'name teacherId')
      .populate('students', 'studentId name')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await Class.countDocuments(query);
    ok(res, classes.map(mapClassToClient), {
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        totalPages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.getClassById = async (req, res) => {
  try {
    const c = await Class.findById(req.params.id)
      .populate('advisor', 'name teacherId phone')
      .populate('lecturer', 'name teacherId phone')
      .populate('students', 'studentId name gender phone status');
    if (!c) return fail(res, 404, '未找到该班级');
    ok(res, mapClassToClient(c));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.createClass = async (req, res) => {
  try {
    const payload = mapClientToClass(req.body || {});
    if (!payload.className || !payload.academy) {
      return fail(res, 400, '缺少必要字段: className | academy');
    }
    
    const exist = await Class.findOne({ className: payload.className });
    if (exist) return fail(res, 400, '班级名称已存在');
    
    const created = await Class.create({ ...payload, studentCount: 0, students: [] });
    const c = await Class.findById(created._id)
      .populate('advisor', 'name')
      .populate('lecturer', 'name');
    ok(res, mapClassToClient(c));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.updateClass = async (req, res) => {
  try {
    const payload = mapClientToClass(req.body || {});
    payload.updatedAt = new Date();
    const updated = await Class.findByIdAndUpdate(req.params.id, payload, { new: true })
      .populate('advisor', 'name')
      .populate('lecturer', 'name')
      .populate('students', 'studentId name');
    
    // 更新学生人数
    if (updated.students) {
      updated.studentCount = updated.students.length;
      await updated.save();
    }
    
    if (!updated) return fail(res, 404, '未找到该班级');
    ok(res, mapClassToClient(updated));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.deleteClass = async (req, res) => {
  try {
    const deleted = await Class.findByIdAndDelete(req.params.id);
    if (!deleted) return fail(res, 404, '未找到该班级');
    ok(res, { id: req.params.id });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

